<?php
/**
 * JoiExtraFields - библиотека для работы с дополнительными полями
 *
 * Core Class
 *
 * @version 1.0 
 * @package JoiExtraFields
 * @filename joiExtraFields.class.php
 * @author JoostinaTeam
 * @copyright (C) 2008-2009 Joostina Team
 * @license GNU GPL 2.0. Пожалуйста, не удаляйте копирайты из исходного кода. Спасибо. 
 *
 **/
 DEFINE('JOIEXTRAFIELDS', '1');
 
 class joiExtraFields extends mosDBTable{
	
	var $_mainframe = null;
	var $_error = null;
    
	var $id = null;
    var $name = null;
    var $type = null;
    var $label = null;
    var $required = null;
    var $extra = null;
    var $published = null;
    var $component = null;
    
    var $_loaded_fields = null;
    var $_loaded_fields_array = array();   
    var $_values = null;
    
    function joiExtrafields($mainframe, $component = ''){
        $this->_mainframe = $mainframe;
        
        $this->mosDBTable('#__joi_extrafields', 'id', $this->_mainframe->_db);
        
        if($component){
            $this->component = $component;
        }    
    }
    
	function check(){
	   
		$query = "SELECT id FROM ".$this->_tbl." WHERE name = '".$this->name."' AND component='".$this->component."' ";
		$this->_db->setQuery($query);
		if($this->_db->loadResult()){
            $this->_error = 'Поле с таким именем уже существует';
            return false;
		}
        return true;
	}
    
    function load_fields($published = null, $ids = array()){

        $where = " WHERE component = '".$this->component."'" ;
        
        if ($ids){
            $ids_ = implode(',', $ids);
            if(count($ids)>1){
                $where .= " AND id IN (".$ids_." ) " ;   
            }
            else{
                $where .= " AND id = ".$ids[0];    
            }            
        }
        
        if($published){
            $where .= ' AND published = 1';     
        }
        
        $sql = 'SELECT *  FROM '.$this->_tbl.$where.' ORDER BY id';        
		$this->_db->setQuery($sql);
        
		$this->_loaded_fields = $this->_db->loadObjectList();
               
    }
    
    function load_fileds_with_values($published = null, $obj_id, $ids = array()){
        $where = " WHERE a.component = '".$this->component."'" ;
        
        if ($ids){
            $ids_ = implode(',', $ids);
            if(count($ids)>1){
                $where .= " AND a.id IN (".$ids_." ) " ;   
            }
            else{
                $where .= " AND a.id = ".$ids[0];    
            }            
        }
        
        if($published){
            $where .= ' AND a.published = 1';     
        }
        
        $sql = 'SELECT a.*, b.* 
        FROM '.$this->_tbl.' AS a 
        LEFT JOIN #__joi_extrafields_values AS b ON (b.field_id = a.id AND b.obj_id = '.$obj_id.' AND b.component = \''.$this->component.'\' ) 
        '.$where.'  ORDER BY a.id';        
		$this->_db->setQuery($sql);
        
		$this->_loaded_fields = $this->_db->loadObjectList();        
    }
    
    
    function loaded_fields_in_array(){
        
		$rows = get_object_vars($this);         

        foreach($this->_loaded_fields as $field){ 
            foreach ($rows as $key => $value) {
                if (substr($key, 0, 1) !== '_') {
                    $this->_loaded_fields_array[$field->name][$key] = $field->$key;
			     }
            } 
            $this->_loaded_fields_array[$field->name]['value'] = $field->value; 
        }
    }
    

    
    //depricated???
    //function load_fields_values($published = 1, $obj_ids = array(), $fields_ids = array()){
        //$this->_values = new joiExtraFieldsValues($this->_mainframe, $this->component);   
        //$this->_values->load_values($published, $obj_ids, $fields_ids);
    //}
    
    
    //выводит поля для заполнения
    function print_all_fields($form_id, $auto_js = 1){
        
        if(!$form_id){
            return false;
        }
        
        $validate = new joiExtraValidation($this->_mainframe, $form_id, $auto_js);
        
        foreach($this->_loaded_fields as $field){            
            $field_type = 'field_'.$field->type;                        
            echo call_user_func(array('joiExtraFieldsTypes', $field_type),$field);
           
        }        
    }
    
    
    //выводит значения всех полей 
    function print_all_values(){
        
        foreach($this->_loaded_fields as $field){            
            echo $field->label. ': '.$field->value.'<br />';           
        }        
    }
    
    //отдает значение определенного свойства поля
    function get_field($field_name, $property = 'value'){
        if($this->_loaded_fields_array && $field_name && isset($this->_loaded_fields_array[$field_name]) && $this->_loaded_fields_array[$field_name]['published'] == 1 ){
            return $this->_loaded_fields_array[$field_name][$property];    
        }   
        else{
            return false;
        } 
    }    
    
    
    function save_fields_values($obj_id){
        
        $extra_field = new joiExtraFieldsValues($this->_mainframe, $this->component);
        
        if(!$this->_loaded_fields){
            $this->load_fields('1');
        }
        
        $sql = 'DELETE FROM `#__joi_extrafields_values` 
        WHERE `obj_id` = '.$obj_id.'               
        AND component = \''.$this->component.'\'';
        $this->_db->setQuery($sql);     
        $this->_db->Query();    
        
        foreach($this->_loaded_fields as $field){            
            if(mosGetParam($_REQUEST, $field->name, null)){             
                
                $extra_field->obj_id = $obj_id;
                $extra_field->component = $this->component;
                $extra_field->field_id = $field->id;
                $extra_field->value = mosGetParam($_REQUEST, $field->name);
                
                if (!$extra_field->store()) {
                    echo "<script> alert('" . $extra_field->getError() . "'); window.history.go(-1); </script>\n";
                    exit();
                }
            }
        }
        
    }
    
    function delete_values($field_id){        
        $sql = 'DELETE FROM `#__joi_extrafields_values` 
        WHERE `field_id` = '.$field_id;
        $this->_db->setQuery($sql);     
        return $this->_db->Query();           
    }
    
    function delete_values_by_obj($obj_id){
        $sql = 'DELETE FROM `#__joi_extrafields_values` 
        WHERE `obj_id` = '.$obj_id.'               
        AND component = \''.$this->component.'\'';
        $this->_db->setQuery($sql);     
        $this->_db->Query();             
    }
    
    function get_list_types(){
        $arr = array();
        $arr[] = mosHTML::makeOption('inputbox', 'Текстовое поле');       
        $arr[] = mosHTML::makeOption('textarea', 'Текстовая область');   
        $arr[] = mosHTML::makeOption('checkbox', 'Чекбокс'); 
        $arr[] = mosHTML::makeOption('radio', 'Переключатель');       
        $arr[] = mosHTML::makeOption('select', 'Выпадающий список');   
        $arr[] = mosHTML::makeOption('image', 'Изображение'); 
        return $arr;           
    }

  
}

class joiExtraValidation {
    
    function joiExtraValidation($mainframe, $form_id, $auto_js = 1){

        $mainframe->addJS($mainframe->getCfg('live_site').'/components/com_joivideo/lib/joiExtraFields/validation/jquery.validate.js','js');
        
        if($auto_js){
            ?>
                <div id="errorBox1" style="display: none;"></div>
                <script>
                $(document).ready(function(){
                    $('.button').live('click', function(){
                        if($(this).hasClass('cancel')){
                            $('#<?php echo $form_id;?>').submit(); 
                            return false;  
                        }
                        else{
                            $('#<?php echo $form_id;?>').validate({    
                                  errorPlacement: function(error, element) {
                                     error.appendTo("#errorBox1");
                                   }
                            });
                            $('#<?php echo $form_id;?>').submit(); 
                            //return false;                       
                        }             
                    })
                });
        
                </script>            
            <?php
        }

     
    }    
}


class joiExtraFieldsValues extends mosDBTable{
    
   	var $_mainframe = null;
	var $_error = null;
	var $field_id = null;
    var $obj_id = null;
    var $component = null;
    var $value = null;
    
    var $_field = null;
    
    var $_loaded_values = null;
    
    function joiExtraFieldsValues($mainframe, $component = ''){
        
        $this->_mainframe = $mainframe;
        
        $this->mosDBTable('#__joi_extrafields_values', '_field', $this->_mainframe->_db);
        
        if($component){
            $this->component = $component;
        }           
    }
    
    function load_values($obj_ids = array(), $fields_ids = array()){

        $where = " WHERE component = '".$this->component."'" ;

        
        if ($obj_ids){
            $ids_ = implode(',', $obj_ids);
            if(count($obj_ids)>1){
                $where .= " AND obj_id IN (".$ids_." ) " ;   
            }
            else{
                $where .= " AND obj_id = ".$obj_ids[0];    
            }            
        }
        
        if ($fields_ids){
            $ids_ = implode(',', $fields_ids);
            if(count($fields_ids)>1){
                $where .= " field_id IN (".$ids_." ) " ;   
            }
            else{
                $where .= " field_id = ".$fields_ids[0];    
            }            
        }

        
        $sql = 'SELECT *  FROM '.$this->_tbl.$where;        
		$this->_db->setQuery($sql);
        
		$this->_loaded_fields = $this->_db->loadObjectList();        
        
    }
    
}

class joiExtraFieldsTypes{
    
    function get_attribs($field, $label = 0){
        
        $attribs = ' ';         
        
        if(!$label){
            
            $attribs .= ' class="inputbox';
            if($field->required){
                $attribs .= ' required';    
            }
            $attribs .= '"';
            
            $attribs .= ' class="inputbox" ';  
            $attribs .= ' name="'.$field->name.'" ';
            $attribs .= ' id="exf_'.$field->name.'" '; 
        } 
        else{
            $attribs .= ' for="exf_'.$field->name.'" id="lbl_'.$field->name.'" ';     
        }  
        
        return $attribs;
    }
    
    function get_label($field){
        $label = '<label '.self::get_attribs($field, 1).'>'.$field->label.'</label>';  
        return $label;  
    }
    
    function field_inputbox($field){
        
        if(isset($field->value)){
            $value = $field->value;
        }
        else{
            $value = '';
        }
        return self::get_label($field).' <input type="text" '.self::get_attribs($field).' value="'.$value.'" />';        
    }
    
    function field_checkbox($field){
        
        if(isset($field->value)){
            $value = $field->value;
        }
        else{
            $value = '';
        }
        
        $checked = '';
        if( $value == 1){
            $checked = ' checked="checked" ';
        }
        
        return self::get_label($field).' <input type="checkbox" '.self::get_attribs($field).' '.$checked.' value="1" />';        
    }
     
    function field_textarea($field){
        
        if(isset($field->value)){
            $value = $field->value;
        }
        else{
            $value = '';
        }
        return self::get_label($field).'<textarea '.self::get_attribs($field).'>'.$value.'</textarea>';    
    }

    
}